package org.jet.emall.prod.controller;

import io.swagger.annotations.ApiOperation;
import org.jet.emall.common.restful.result.CommonResult;
import org.jet.emall.prod.dto.NewOrderDTO;
import org.jet.emall.prod.dto.OrderDTO;
import org.jet.emall.prod.model.NewOrderModel;
import org.jet.emall.prod.service.CustomOrderService;
import org.jet.emall.prod.service.CustomProductService;
import org.jet.emall.prod.transfer.OrderVoTransfer;
import org.jet.emall.prod.vo.OrderVO;
import org.jet.emall.prod.wrapper.OrderCodeAndStatusWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-04-30 11:30
 */
@RestController
public class OrderController {

    @Autowired
    private CustomOrderService customOrderService;

    @Autowired
    private CustomProductService customProductService;

    @ApiOperation(value = "创建订单")
    @RequestMapping(value = "/orders",method = RequestMethod.POST)
    public CommonResult<String> addOrder(@RequestBody NewOrderModel model){
        NewOrderDTO dto = OrderVoTransfer.INSTANCE.toDto(model);
        Long id = customOrderService.save(dto);

        return CommonResult.created(id.toString(),"新建订单成功");
    }


    @RequestMapping(value = "/orders/{customerId}",method = RequestMethod.GET)
    public CommonResult<List<OrderVO>> list(@PathVariable Long customerId){
        List<OrderDTO> dtoList = customOrderService.list(customerId);
        List<OrderVO> voList = OrderVoTransfer.INSTANCE.toVoList(dtoList);

        return CommonResult.success(voList,"获取订单列表成功");
    }


    @RequestMapping(value = "/orders/status",method = RequestMethod.PATCH)
    public CommonResult<Object> updateOrderStatus(@RequestBody @Valid OrderCodeAndStatusWrapper wrapper){
        customOrderService.update(wrapper.getCode(),wrapper.getStatus());
        return CommonResult.success("修改订单状态成功");
    }

    @RequestMapping(value = "/wx/orders/status",method = RequestMethod.PUT)
    public CommonResult<Object> wxUpdateOrderStatus(@RequestBody @Valid OrderCodeAndStatusWrapper wrapper){
        customOrderService.update(wrapper.getCode(),wrapper.getStatus());
        return CommonResult.success("修改订单状态成功");
    }


    @RequestMapping(value = "/orders/one/{id}",method = RequestMethod.GET)
    public CommonResult<OrderVO> getOrder(@PathVariable Long id){
        OrderDTO order = customOrderService.getOrderById(id);
        OrderVO orderVO = OrderVoTransfer.INSTANCE.toVo(order);
        orderVO.setItems(OrderVoTransfer.INSTANCE.toItemVoList(order.getItems()));
        return CommonResult.success(orderVO,"获取订单详情成功");
    }
}
